import { Component, signal, computed, inject, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { MatIconModule, MatIconRegistry } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatPaginatorModule } from '@angular/material/paginator';
import { ChangeDetectionStrategy } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

interface IconItem {
  name: string;
  tags: string[];
}

@Component({
  selector: 'cne-material-icons',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    MatIconModule,
    MatButtonModule,
    MatCardModule,
    MatFormFieldModule,
    MatInputModule,
    MatProgressSpinnerModule,
    MatTooltipModule,
    MatPaginatorModule
  ],
  templateUrl: './material-icons.component.html',
  styleUrls: ['./material-icons.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MaterialIconsComponent implements OnInit {
  private http = inject(HttpClient);
  private matIconRegistry = inject(MatIconRegistry);
  private domSanitizer = inject(DomSanitizer);

  // 搜索关键词
  searchKeyword = signal<string>('');
  
  // 加载状态
  isLoading = signal<boolean>(true);
  
  // 所有图标数据
  allIcons = signal<IconItem[]>([]);
  
  // 分页配置
  pageSize = signal<number>(50);
  currentPage = signal<number>(0);
  
  // 过滤后的图标
  filteredIcons = computed(() => {
    const keyword = this.searchKeyword().toLowerCase();
    if (!keyword) {
      return this.allIcons();
    }
    return this.allIcons().filter(icon => 
      icon.name.toLowerCase().includes(keyword) ||
      icon.tags.some(tag => tag.toLowerCase().includes(keyword))
    );
  });
  
  // 分页后的图标
  paginatedIcons = computed(() => {
    const filtered = this.filteredIcons();
    const pageSize = this.pageSize();
    const currentPage = this.currentPage();
    const startIndex = currentPage * pageSize;
    const endIndex = startIndex + pageSize;
    return filtered.slice(startIndex, endIndex);
  });
  
  // 总页数
  totalPages = computed(() => {
    const filtered = this.filteredIcons();
    return Math.ceil(filtered.length / this.pageSize());
  });

  // 统计信息
  stats = computed(() => {
    const icons = this.allIcons();
    const materialIcons = icons.filter(icon => !icon.name.startsWith('mdi:'));
    const mdiIcons = icons.filter(icon => icon.name.startsWith('mdi:'));
    
    return {
      total: icons.length,
      material: materialIcons.length,
      mdi: mdiIcons.length
    };
  });

  ngOnInit() {
    this.loadIconsFromLocal();
    this.registerMDIIcons();
  }

  /**
   * 注册 MDI 图标到 MatIconRegistry
   */
  private registerMDIIcons() {
    // 使用 SVG 图标解析器动态加载 MDI 图标
    this.matIconRegistry.addSvgIconResolver((name, namespace) => {
      if (namespace === 'mdi') {
        // 动态生成 MDI SVG 文件路径
        return this.domSanitizer.bypassSecurityTrustResourceUrl(`./assets/mdi/${name}.svg`);
      } else {
        return null;
      }
    });
  }

  /**
   * 从本地 JSON 文件加载图标数据
   */
  private async loadIconsFromLocal() {
    try {
      this.isLoading.set(true);
      
      // 从本地 assets 目录加载图标数据
      const icons = await this.http.get<IconItem[]>('/assets/metadata/material-icons.json').toPromise();
      
      if (icons && Array.isArray(icons)) {
        this.allIcons.set(icons);
      } else {
        throw new Error('本地图标数据格式不正确');
      }
    } catch (error) {
      console.error('从本地文件加载图标失败:', error);
      // 使用备用图标
      this.allIcons.set(this.getFallbackIcons());
    } finally {
      this.isLoading.set(false);
    }
  }

  /**
   * 获取备用图标列表
   */
  private getFallbackIcons(): IconItem[] {
    return [
      { name: 'home', tags: ['house', 'building', 'residence'] },
      { name: 'search', tags: ['find', 'look', 'magnify'] },
      { name: 'favorite', tags: ['heart', 'like', 'love'] },
      { name: 'settings', tags: ['gear', 'configuration', 'options'] },
      { name: 'person', tags: ['user', 'account', 'profile'] },
      { name: 'email', tags: ['mail', 'message', 'communication'] },
      { name: 'phone', tags: ['call', 'telephone', 'contact'] },
      { name: 'location_on', tags: ['place', 'position', 'map'] },
      { name: 'schedule', tags: ['time', 'calendar', 'clock'] },
      { name: 'notifications', tags: ['alert', 'bell', 'reminder'] },
      { name: 'shopping_cart', tags: ['basket', 'buy', 'purchase'] },
      { name: 'star', tags: ['rating', 'favorite', 'bookmark'] },
      { name: 'add', tags: ['plus', 'create', 'new'] },
      { name: 'edit', tags: ['modify', 'change', 'update'] },
      { name: 'delete', tags: ['remove', 'trash', 'bin'] },
      { name: 'close', tags: ['cancel', 'exit', 'dismiss'] },
      { name: 'check', tags: ['done', 'complete', 'success'] },
      { name: 'arrow_back', tags: ['previous', 'back', 'left'] },
      { name: 'arrow_forward', tags: ['next', 'forward', 'right'] },
      { name: 'menu', tags: ['hamburger', 'navigation', 'list'] }
    ];
  }

  /**
   * 复制图标名称到剪贴板
   */
  copyIconName(iconName: string) {
    navigator.clipboard.writeText(iconName).then(() => {
      // 复制成功，可以添加用户反馈
    }).catch(err => {
      console.error('复制失败:', err);
    });
  }

  /**
   * 获取图标显示名称（去掉 mdi: 前缀）
   */
  getDisplayName(iconName: string): string {
    return iconName.startsWith('mdi:') ? iconName.substring(4) : iconName;
  }

  /**
   * 检查是否为 MDI 图标
   */
  isMDIIcon(iconName: string): boolean {
    return iconName.startsWith('mdi:');
  }

  /**
   * 获取图标类型标签
   */
  getIconType(iconName: string): string {
    return this.isMDIIcon(iconName) ? 'MDI' : 'Material';
  }

  /**
   * 获取图标类型颜色
   */
  getIconTypeColor(iconName: string): string {
    return this.isMDIIcon(iconName) ? '#1976d2' : '#4caf50';
  }

  /**
   * 分页控制方法
   */
  onPageChange(event: any) {
    this.currentPage.set(event.pageIndex);
    this.pageSize.set(event.pageSize);
  }

  /**
   * 搜索时重置到第一页
   */
  onSearchChange() {
    this.currentPage.set(0);
  }

  /**
   * 获取当前页显示范围
   */
  getPageRange() {
    const filtered = this.filteredIcons();
    const pageSize = this.pageSize();
    const currentPage = this.currentPage();
    const startIndex = currentPage * pageSize + 1;
    const endIndex = Math.min((currentPage + 1) * pageSize, filtered.length);
    return { startIndex, endIndex, total: filtered.length };
  }
}